
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.util.*;

public class AreaJsonToSql {
    static class RegionNode {
        public String code;
        public String name;
        public List<RegionNode> children;
    }

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<RegionNode> data = mapper.readValue(
                new File("doc/sql/pcas-code.json"),
                new TypeReference<List<RegionNode>>() {}
        );

        List<String> sqls = new ArrayList<>();
        for (RegionNode node : data) {
            walk(node, 1, null, sqls);
        }

        try (Writer writer = new OutputStreamWriter(new FileOutputStream("d:/area.sql"), "UTF-8")) {
            for (String line : sqls) {
                writer.write(line);
            }
        }
        System.out.println("SQL生成完毕，已保存到 d:/area.sql");
    }

    private static void walk(RegionNode node, int level, String parentCode, List<String> sqls) {
        String parent = (parentCode == null) ? "NULL" : "'" + parentCode + "'";
        sqls.add(String.format(
                "INSERT INTO sys_region (code, name, level, parentCode) VALUES ('%s', '%s', %d, %s);\n",
                node.code, node.name.replace("'", "''"), level, parent
        ));
        if (node.children != null) {
            for (RegionNode child : node.children) {
                walk(child, level + 1, node.code, sqls);
            }
        }
    }
}
